package com.yzz.shopping.ui.widget

import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.youth.banner.listener.OnPageChangeListener
import com.yzz.shopping.GlideHttpUtils
import com.yzz.shopping.GlideHttpUtils.GlideListener
import com.yzz.shopping.R
import com.yzz.shopping.entity.GlideRecommendBean
import com.yzz.shopping.entity.SelectChangeBean
import com.yzz.shopping.entity.ShoppingHotBean
import com.yzz.shopping.inter.IItemSelectListener
import com.yzz.shopping.ui.adapter.BannerSelectAdapter
import com.yzz.shopping.ui.adapter.HotBannerAdapter
import com.yzz.shopping.utils.CheckActivityUtils
import com.yzz.shopping.utils.ToolsUtils
import kotlinx.android.synthetic.main.view_banner.view.*

/**
 * @Author : yangzuozhe
 * @Time : On 2022/3/31 10:42
 *
 * @Description : BannerView
 */
class BannerView : FrameLayout {
    private var mBannerSelectAdapter: BannerSelectAdapter? = null
    private var mBanner: MyBanner<GlideRecommendBean?, HotBannerAdapter?>? = null

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        LayoutInflater.from(context).inflate(R.layout.view_banner, this)
        mBanner = findViewById(R.id.mShoppingBanner)
    }

    private fun initBanner(
        activity: FragmentActivity?,
        number: Int,
        loopTime: Long,
        listener: IItemSelectListener<GlideRecommendBean?>?,
        gotoUrlListener: IItemSelectListener<String?>?,
    ) {
        mBanner?.setLoopTime(loopTime)
        requestData(activity, number, listener, gotoUrlListener)
    }

    /**
     * 如果你的轮播图在 activity 就用这个
     * @param number 轮播图总数
     * @param loopTime 自动轮播间隔时间（毫秒）
     */
    fun requestActivityHot(
        activity: FragmentActivity?,
        number: Int,
        loopTime: Long,
        listener: IItemSelectListener<GlideRecommendBean?>?,
        gotoUrlListener: IItemSelectListener<String?>?,
    ) {
        mBanner?.addBannerLifecycleObserver(activity)
        initBanner(activity, number, loopTime, listener, gotoUrlListener)
    }

    /**
     * 如果你的轮播图在 fragment 就用这个
     *
     * @param number 轮播图总数
     * @param loopTime 自动轮播间隔时间（毫秒）
     */
    fun requestFragmentHot(
        activity: FragmentActivity?,
        fragment: Fragment,
        number: Int,
        loopTime: Long,
        listener: IItemSelectListener<GlideRecommendBean?>?,
        gotoUrlListener: IItemSelectListener<String?>?,
    ) {
        mBanner?.addBannerLifecycleObserver(fragment)
        initBanner(activity, number, loopTime, listener, gotoUrlListener)
    }

    private fun requestData(
        activity: FragmentActivity?,
        number: Int,
        listener: IItemSelectListener<GlideRecommendBean?>?,
        gotoUrlListener: IItemSelectListener<String?>?,
    ) {
        GlideHttpUtils.getInstacne()
            .requestHost(number, object : GlideListener<ShoppingHotBean?> {

                override fun onSuccess(bean: ShoppingHotBean?) {
                    bean?.let {
                        setBanner(activity, it, listener, gotoUrlListener)
                    }
                }

                override fun onError(e: String) {

                }
            })
    }


    private fun setBanner(
        activity: FragmentActivity?,
        shoppingHotBean: ShoppingHotBean?,
        listener: IItemSelectListener<GlideRecommendBean?>?,
        gotoUrlListener: IItemSelectListener<String?>?,
    ) {
        shoppingHotBean?.let { bean ->
            val titleBarBean = shoppingHotBean.titleBar
            titleBarBean?.let { titleBar ->
                val titleIcon = titleBar.titleIcon
                if (!TextUtils.isEmpty(titleIcon)) {
                    mIvBannerTitleImg?.visibility = View.VISIBLE
                    if (activity != null && !CheckActivityUtils.isDestroy(activity) && mIvBannerTitleImg != null) {
                        Glide.with(activity).asBitmap().load(titleIcon).into(mIvBannerTitleImg)
                    }
                } else {
                    val title = titleBar.title
                    if (!TextUtils.isEmpty(title)) {
                        mTvBannerTitle.visibility = VISIBLE
                        mTvBannerTitle?.text = title
                    }
                }
                if (!TextUtils.isEmpty(titleBar.gotoText)) {
                    mTvGotoTitle?.text = titleBar.gotoText
                    mTvGotoTitle?.visibility = View.VISIBLE
                    mTvGotoTitle?.setOnClickListener {
                        gotoUrlListener?.onClick(titleBar.gotoUrl)
                    }
                }
                if (activity != null && !CheckActivityUtils.isDestroy(activity) && mIvGotoUrl != null) {
                    Glide.with(activity).asBitmap().load(titleBar.gotoIcon).into(mIvGotoUrl)
                }
            }

            val list = bean.glideRecommendBeanArrayList
            if (list != null && list.isNotEmpty()) {
                val hotAdapter = HotBannerAdapter(activity, list)
                hotAdapter.setItemListener(listener)
                mBanner?.setAdapter(hotAdapter)
                mBanner?.addOnPageChangeListener(object : OnPageChangeListener {
                    override fun onPageScrolled(
                        position: Int,
                        positionOffset: Float,
                        positionOffsetPixels: Int,
                    ) {
                    }

                    override fun onPageSelected(position: Int) {
                        mBannerSelectAdapter?.changeSelect(position)
                    }

                    override fun onPageScrollStateChanged(state: Int) {
                    }

                })
                initSelectView(list.size)
            }
        }
    }

    private fun initSelectView(size: Int) {
        val list = arrayListOf<SelectChangeBean>()
        for (i in 0 until size) {
            if (i == 0) {
                list.add(SelectChangeBean(true))
            } else {
                list.add(SelectChangeBean(false))
            }
        }
        mBannerSelectAdapter = BannerSelectAdapter(list)
        mLLShoppingSelect.layoutManager = LinearLayoutManager(context).apply {
            orientation = LinearLayoutManager.HORIZONTAL
        }
        mLLShoppingSelect.adapter = mBannerSelectAdapter
    }


    /**
     * 停止轮播
     */
    fun stopBanner() {
        mBanner?.stop()
    }

    /**
     * 轮播销毁
     */
    fun destroyBanner() {
        mBanner?.destroy()
    }

    /**
     * 恢复轮播
     */
    fun startBanner() {
        mBanner?.start()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        destroyBanner()
    }
}